//
//  FoodOrderFormVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2021/9/15.
//  Copyright © 2021 zwb. All rights reserved.
//

import UIKit

class ZyaFoodOrderFormVC: GlobalFormVC,refreshable,operatable,DateWidgetable {
    
    var model = ZyaFoodOrderModel(JSON:["":""])!
  
    var currentMark = 0
    var idKey = ""
     
    
    var item1 :KSFormHItem = {
        let appe = KSFormHAppear()
           
        let v = KSFormHItem(title: "下单公司",appearance:appe)
        return v
    }()
    var item2 :KSFormHItem = {
        let appe = KSFormHAppear()
           
        let v = KSFormHItem(title: "客户",appearance:appe)
        return v
    }()
    var itemSubClient :KSFormHItem = {
        let appe = KSFormHAppear()
           
        let v = KSFormHItem(title: "下属客户",appearance:appe)
        return v
    }()
    var item4 :KSFormHItem = {
        let v = KSFormHItem(title: "可用余额")
        v.disabled = true
        return v
    }()
    
    var item5 :KSFormHItem = {
        let appe = KSFormHAppear()
           
        let v = KSFormHItem(title: "购货日期",appearance:appe)
        return v
    }()
    
    var itemWarehouse :KSFormHItem = {
        let appe = KSFormHAppear()
           
        let v = KSFormHItem(title: "仓库",appearance:appe)
        return v
    }()
    
    var itemCarNo :KSFormHItem = {
        let appe = KSFormHAppear()
           
        let v = KSFormHItem(title: "车牌号",appearance:appe)
        return v
    }()
    
    var itemRemark :KSFormHItem = {
        let appe = KSFormHAppear()
           
        let v = KSFormHItem(title: "备注",appearance:appe)
        return v
    }()
    
    lazy var bottomV:ZyaFoodOrdFormBottomV = {
        let v = ZyaFoodOrdFormBottomV()
        return v
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        switch excuteType {
        case .add,.copy:
            self.title = "新增订单"
        case .fix:
            self.title = "编辑订单"
        case .view:
            self.title = "查看订单"
        default:
            break
        }
        
        if excuteType == .view || excuteType == .fix || excuteType == .copy {
            KSNetwork.shared.doRequest(API.pFoodGetForm(id_key: self.model.idKey.unwrap)) { (data:BaseResult<ZyaFoodOrderModel>) in
                if data.flag == TRUE {
                    if let info = data.info_object {
                        self.model = info
                     
                        if self.excuteType == .copy {
                            
                            self.model.sDate = Date.todayAfter(1)
                            self.model.idKey = nil
                            self.model.sSumNumber = nil
                            self.model.sTotalMoney = nil
                            self.model.sAuditDt = nil
                            self.model.sAuditId = nil
                            self.model.sNo = nil
                            self.model.sAuditNm = nil
                            self.model.sCreateTm = nil
                            self.model.sUpdateTm = nil
                            self.model.sAuditMark = nil
                            self.refreshPrice()
                            
                        }
                        self.tableVw.reloadData()
                        self.configBottom()
                        self.configDataSource()
                         self.queryBalance()
                    }
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
        } else {
            self.model.sStaffId = USERINFO.usrid
            self.model.sStaffNm = USERINFO.usrdesc
            
            
            self.model.sOrgNm = USERINFO.commpayNm
            self.model.sOrgId = USERINFO.companyId
 
            if USERINFO.isSpywy == "1" {
                self.model.sSalersId = USERINFO.usrid
                self.model.sSalersNm = USERINFO.usrdesc
            } else {
                
                self.model.sClientId = USERINFO.kfId
                self.model.sClientNm = USERINFO.kfName
             }
            
            self.model.sDate = Date.todayAfter(1)
            self.model.sBranchClientId = USERINFO.kClientBranchId
            self.model.sBranchClientNm = USERINFO.kClientBranchNm
            self.model.avaliableMoney = "0"
             self.configBottom()
            self.configDataSource()
        }
        

        self.tableVw.register(ZyaFoodOrderFormCell.self, forCellReuseIdentifier: ZyaFoodOrderFormCell.identifier)


        
        let footerV = UIView(frame: CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 45))
        footerV.backgroundColor = .clear
        let btn = ZyaLLLXButton(frame: CGRect(x: (KSGlobal.screenW - 120)/2, y: 2, width: 120, height: 40))
        btn.setTitle("添加产品", for: .normal)
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        btn.setImage(UIImage(named: "xinzeng"), for: .normal)
        btn.setTitleColor(.darkGray, for: .normal)
        btn.addTarget(self, action: #selector(addProduct), for: .touchUpInside)
        footerV.addSubview(btn)
        if excuteType == .add || excuteType == .fix || excuteType == .copy {
            self.tableVw.tableFooterView = footerV
        }
        self.tableVw.backgroundColor = UIColor(kshex: "#f4f4f4")
        
        self.view.addSubview(bottomV)
        bottomV.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(60)
        }
        
        bottomV.payBtn.addTouchUpInSideAction { _ in
            
            self.submitAction()
        }
        self.configView()
        self.configAction()
        self.configDataSource()
     
    
    }
    
    func refreshPrice() {
        if self.model.detail.count > 0 {
            let goodids = self.model.detail.compactMap { $0.sGoodsId }.joined(separator: ",")
            KSNetwork.shared.doRequest(API.pFoodQueryGoodsPrice(s_org_id: self.model.sOrgId.unwrap, s_client_id: self.model.sClientId.unwrap, s_goods_id: goodids,s_date: self.model.sDate.unwrap,s_customer_branch_id: self.model.sBranchClientId.unwrap)) { (data:BaseResult<ZyaFoodOrderDetail>) in
                if data.flag == TRUE {
                    if let infos = data.infoArrCombine {
                        
                        for i in 0..<self.model.detail.count {
                            
                            let arr = infos.filter { $0.sGoodsId == self.model.detail[i].sGoodsId }
                            if let dModel = arr.first {
                                self.model.detail[i].sRemark = nil
                                self.model.detail[i].sPrice = dModel.sPrice
                                self.model.detail[i].sTax = dModel.sTax
                                self.model.detail[i].sWeightRatio = dModel.sWeightRatio
                                self.countMoneyAndMTax(row: i)
                            }
                            
                        }
                        self.tableVw.reloadData()
                        self.configBottom()
                    }
                }
            }
            
        }
    }
    
    func configView() {
        self.bg.add(item1).add(item2)
        if ztbAppTypeDesc == .aw {
            bg.add(itemSubClient)
        }
            
            bg.add(item4).add(item5)
        
//        if TenderAppear.shared.projectType == .awClient {
            bg.add(itemWarehouse)
                .add(itemCarNo)
                .add(itemRemark)
//        }
     
        if USERINFO.isSpywy == "1" && USERINFO.kClientBranchId.unwrap == "" {
            item2.disabled = false
        } else {
            item2.disabled = true
        }
        if USERINFO.kClientBranchId.unwrap != "" {
            itemSubClient.disabled = true
        } else {
            itemSubClient.disabled = false
        }
        
      
        header.ks_height = bg.frame.maxY
        tableVw.tableHeaderView = header
    }
    func configAction() {
        self.item1.actionClosure = {
            var needConfirm = true
            if self.model.sOrgId.unwrap.isEmpty {
                needConfirm = false
            }
             if self.model.detail.count < 1 {
                needConfirm = false
            }
            
            
            if needConfirm {
                alertUtil(self, title: "切换公司会清空产品信息，确认切换", operateS: [nameAction(name: "确定", action: { _ in
                    
                    self.queryOrgJudge()
                    
                })])
            } else {
                self.queryOrgJudge()
            }
            
            
        }
        
        if USERINFO.isSpywy == "1" && USERINFO.kClientBranchId.unwrap == "" {
            self.item2.actionClosure = {
               
                    guard !self.model.sOrgId.unwrap.isEmpty else {
                        KSToast("先选公司")
                        return
                    }
                    
                    var needConfirm = true
                    if self.model.sClientId.unwrap.isEmpty {
                        needConfirm = false
                    }
               
                        if self.model.detail.count < 1 {
                            needConfirm = false
                        }
                    
                    
                    if needConfirm {
                        alertUtil(self, title: "切换客户会清空下属客户和产品信息，确认切换", operateS: [nameAction(name: "确定", action: { _ in
                            self.queryClient()
                        })])
                    } else {
                        self.queryClient()
                    }
                    
                
            }
        }
        
        if USERINFO.kClientBranchId.unwrap == "" {
            self.itemSubClient.actionClosure = {
                guard !self.model.sOrgId.unwrap.isEmpty else {
                    KSToast("先选公司")
                    return
                }
                guard !self.model.sClientId.unwrap.isEmpty else {
                    KSToast("先选客户")
                    return
                }
                var needConfirm = true
                
                    if self.model.detail.count < 1 {
                        needConfirm = false
                    }
                
                 if needConfirm {
                    alertUtil(self, title: "切换下属客户会清空产品信息，确认切换", operateS: [nameAction(name: "确定", action: { _ in
                        self.queryFollowClient()
                    })])
                } else {
                    self.queryFollowClient()
                }

            }
        }

        self.item5.actionClosure = {
            self.showDateSelect(self) { str in
                self.model.sDate = str
                self.configDataSource()
                self.refreshPrice()
            }
        }
        
        self.itemWarehouse.actionClosure = {
            let vc = KSSingleSelectNetUtil()
            vc.title = "仓库选择"
            vc.kSSingleSelectNetNetwork = { [weak self] page, size, keyword in
                
                guard let self = `self` else { return }
                
                KSNetwork.shared.fetchObjectsArray(API.queryOrgStorage(s_org_id: self.model.sOrgId.unwrap, s_title: keyword), successHandle: { (data: [ZyaWarehouseModel]) in
                    
                    if page == 1 {
                        vc.allArr.removeAll()
                    }
                    
                    vc.showData(arr: data)
                    
                }, errorHandle:{
                    KSToast("仓库出错")
                })
            }
            
            vc.kSSingleSelectNetShowCell = { cell,model in
                
                var contArr:[(String, String?)]!
                
                contArr = [
                    ("仓库名称", "\((model as! ZyaWarehouseModel).sStorageNm.unwrap)")
                ]
                
                cell.setDataSource(contentArr: contArr)
            }
            
            vc.backClosure = { one in
                
                self.model.sStorageId = (one as! ZyaWarehouseModel).sStorageId
                self.model.sStorageNm = (one as! ZyaWarehouseModel).sStorageNm
                
                self.configDataSource()
                
            }
            
            self.navigationController?.pushViewController(vc,animated:true)

        }
        
        self.itemRemark.textValueChangeClo = { str in
            self.model.sRemark = str
        }
        
        self.itemCarNo.textValueChangeClo = { str in
            self.model.sCarNo = str
        }
    }
    
    func configDataSource() {
        self.item1.setVal(self.model.sOrgNm)

        self.item2.setVal(self.model.sClientNm)
        self.itemSubClient.setVal(self.model.sBranchClientNm)
        self.item4.setVal(self.model.avaliableMoney)

        self.item5.setVal(self.model.sDate)
        
//        if TenderAppear.shared.projectType == .awClient {
            self.itemWarehouse.setVal(self.model.sStorageNm)
            self.itemCarNo.setVal(self.model.sCarNo)
            self.itemRemark.setVal(self.model.sRemark)
//        }
    }
    
    func  queryFollowClient() {
        KSNetwork.shared.doRequest(API.queryBranchClient(s_title: "", s_client_id: self.model.sClientId.unwrap)) { (data:BaseResult<BraClientModel>) in
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    
                    var allArr = [nameAndModel<BraClientModel>]()
                    for item in infos {
                        let one_x = nameAndModel(shows: [item.s_branch_client_nm.unwrap], model: item)
                        allArr.append(one_x)
                    }
                    let cle:(nameAndModel<BraClientModel>)->() = { one in
                        
                        if  self.model.sBranchClientId == one.model.s_branch_client_id {
                            
                        } else {
                            self.model.sBranchClientNm = one.model.s_branch_client_nm
                            self.model.sBranchClientId = one.model.s_branch_client_id
                            self.queryBalance()
                            self.model.detail.removeAll()
                            self.configDataSource()
                            self.tableVw.reloadData()
                         }
                    }
                    let vc = KSSingleSelectUtil.initWithNav(title: "下属客户", allArr: allArr, backClosure: cle)
                    self.present_FullScreen(to: vc)
                    
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    func queryClient() {
        
        KSNetwork.shared.doRequest(API.pFoodQueryClient(page: "1", size: "100", s_title: "", s_staff_id: USERINFO.usrid.unwrap, s_org_id: self.model.sOrgId.unwrap)) { (data:BaseResult<FOOrgModel>) in
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    
                    var allArr = [nameAndModel<FOOrgModel>]()
                    for item in infos {
                        let one_x = nameAndModel(shows: [item.client_nm.unwrap], model: item)
                        allArr.append(one_x)
                    }
                    let cle:(nameAndModel<FOOrgModel>)->() = { one in
                        
                        if  self.model.sClientId == one.model.client_id {
                            
                        } else {
                            self.model.sClientNm = one.model.client_nm
                            self.model.sClientId = one.model.client_id
                            
                            self.model.sBranchClientNm = ""
                            self.model.sBranchClientId = ""
                            
                            self.queryBalance()
                            self.model.detail.removeAll()
                            self.configDataSource()
                            self.tableVw.reloadData()
                        }
                        
                    }
                    let vc = KSSingleSelectUtil.initWithNav(title: "客户", allArr: allArr, backClosure: cle)
                    self.present_FullScreen(to: vc)
                    
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    
    func queryOrgJudge() {
        if USERINFO.isSpywy == "1" {
            self.queryOrgByStaffNet()
        } else {
            self.queryOrgNet()
        }
    }
    
    func queryOrgNet() {
        KSNetwork.shared.doRequest(API.pFoodQueryOrg(s_title: "", s_client_id: USERINFO.usrid.unwrap)) { (data:BaseResult<FOOrgModel>) in
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    
                    var allArr = [nameAndModel<FOOrgModel>]()
                    for item in infos {
                        let one_x = nameAndModel(shows: [item.org_name.unwrap], model: item)
                        allArr.append(one_x)
                    }
                    let cle:(nameAndModel<FOOrgModel>)->() = { one in
                        if self.model.sOrgId == one.model.org_code {
                            
                        } else {
                            self.model.sOrgId = one.model.org_code
                            self.model.sOrgNm = one.model.org_name
                            self.model.sClientNm = one.model.client_nm
                            self.model.sClientId = one.model.client_id
                            
                            self.model.sStaffNm = one.model.s_staff_nm
                            self.model.sStaffId = one.model.s_staff_id
                            self.model.sSalersId = one.model.s_staff_id
                            self.model.sSalersNm = one.model.s_staff_nm
                            
                            self.queryBalance()
                            self.model.detail.removeAll()
                            self.configDataSource()
                            self.tableVw.reloadData()
                        }
                        
                    }
                    let vc = KSSingleSelectUtil.initWithNav(title: "下单公司", allArr: allArr, backClosure: cle)
                    self.present_FullScreen(to: vc)
                    
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    func queryOrgByStaffNet() {
        KSNetwork.shared.doRequest(API.pFoodQueryOrgByStaff(s_title: "", s_staff_id: USERINFO.usrid.unwrap)) { (data:BaseResult<FOOrgModel>) in
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    
                    var allArr = [nameAndModel<FOOrgModel>]()
                    for item in infos {
                        let one_x = nameAndModel(shows: [item.org_name.unwrap], model: item)
                        allArr.append(one_x)
                    }
                    let cle:(nameAndModel<FOOrgModel>)->() = { one in
                        if self.model.sOrgId == one.model.org_code {
                            
                        } else {
                            self.model.sOrgId = one.model.org_code
                            self.model.sOrgNm = one.model.org_name
 
                            self.model.sClientNm = nil
                            self.model.sClientId = nil
                            self.model.sBranchClientNm = nil
                            self.model.sBranchClientId = nil
                            
                            self.model.detail.removeAll()
                            self.tableVw.reloadData()
                            self.configDataSource()
                        }
                        
                    }
                    let vc = KSSingleSelectUtil.initWithNav(title: "下单公司", allArr: allArr, backClosure: cle)
                    self.present_FullScreen(to: vc)
                    
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    
    
    func queryBalance() {
        KSNetwork.shared.doRequest(API.pFoodQueryBalance(s_org_id: self.model.sOrgId.unwrap, s_client_id: self.model.sClientId.unwrap)) { (data:BaseResult<OperateResult>) in
            if data.flag == TRUE {
                if let info = data.infoDic {
                    self.model.avaliableMoney = info["s_money"].unwrap
                    self.configDataSource()
                }
            }
        }
    }
    
    @objc private func addProduct() {
        guard !self.model.sOrgId.unwrap.isEmpty else {
            KSToast("先选公司")
            return
        }
        guard !self.model.sClientId.unwrap.isEmpty else {
            KSToast("先选客户")
            return
        }

        
        
        let vc = ZyaChooseProSegVC()
        vc.productClosure = { arr in
            let narr = arr.compactMap { one -> ZyaFoodOrderDetail in
                var newone = ZyaFoodOrderDetail(JSON: ["":""])!
                newone.sGoodsId = one.sGoodsId
                newone.sWeightRatio = one.sWeightRatio
                newone.sSpec = one.sSpec
                newone.sSaleUnit = one.sSaleUnit
                newone.sStandard = one.sStandard
                newone.sName = one.sName
                newone.sCode = one.sCode
                newone.sPrice = one.sPrice
                newone.sTax = one.sTax
                newone.sSaleUnit = "1"
                newone.sCompanyGoodsTreeNm = one.sCompanyGoodsTreeNm
                return newone
            }
            
            if self.model.detail.count > 0 {
                let oldArr = self.model.detail.compactMap { $0.sGoodsId }
                let farr = narr.filter { one in
                    if oldArr.contains(where: { goodsid in
                        goodsid == one.sGoodsId
                    }) {
                        return false
                    } else {
                        return true
                    }
                }
                self.model.detail += farr
            } else {
                self.model.detail = narr
            }
            self.tableVw.reloadData()
            self.configBottom()
            self.refreshPrice()
        }
        vc.s_orgid = self.model.sOrgId.unwrap
        vc.clientid = self.model.sClientId.unwrap
        vc.s_customer_branch_id = self.model.sBranchClientId.unwrap
        vc.s_date = self.model.sDate.unwrap
        self.navigationController?.pushViewController(vc, animated: true)
    }
    func configBottom() {
        
        if excuteType == .add || excuteType == .fix || excuteType == .copy {
            bottomV.payBtn.isHidden = false
        } else {
            bottomV.payBtn.isHidden = true
        }
        
        if self.model.detail.count > 0 {
            bottomV.badgeLabel.isHidden = false
            bottomV.badgeLabel.text = "\(model.detail.count)"
            let sumWeight = model.detail.compactMap { doubleTran($0.sWeight) }.reduce(0, +)
            let sumMoney = model.detail.compactMap { doubleTran($0.sMoney) }.reduce(0, +)
            let sumNum = model.detail.compactMap { doubleTran($0.sNum) }.reduce(0, +)
            
            self.model.sSumNumber = sumNum.roundTo(3)
            self.model.sTotalMoney = sumMoney
            
            let labelText2 = "合计" + "￥\(sumMoney.twoZero)"
            let smokedLimitAttr2 = NSMutableAttributedString(string: labelText2)
            smokedLimitAttr2.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: (labelText2 as NSString).range(of: "￥\(sumMoney.twoZero)"))
            bottomV.titleLab.attributedText = smokedLimitAttr2
            
            bottomV.subtitleLab.text = "\(sumWeight.threeZero)kg"
        } else {
            bottomV.badgeLabel.isHidden = true
            bottomV.titleLab.text = "合计"
            bottomV.subtitleLab.text = "0.000kg"
        }
    }
    
    @objc private func submitAction() {
        
        view.endEditing(true)
        
        let vali = Validation()
        vali.required(value: self.model.sOrgId, msg: "下单公司不为空")
        vali.required(value: self.model.sClientId, msg: "客户不为空")
        
        vali.required(value:self.model.detail, msg: "产品不为空")
        if  self.model.detail.count > 0 {
            vali.expression(model.detail.count > 0, msg: "产品不为空")
            for i in 0..<model.detail.count {
                vali.required(value: model.detail[i].sAuxNum, msg: "第\(i + 1)个产品，数量不能为空!")
                vali.required(value: model.detail[i].sWeight, msg: "第\(i + 1)个产品，重量不能为空!")
            }
        }
        
        guard vali.validate() else {
            return
        }
        
        
//        if TenderAppear.shared.projectType == .awClient {
   
            
            let beforeMoney = doubleTran(model.avaliableMoney)
            let beforeStr = "\(String(format: "%.2f", beforeMoney))"
            
            let money = model.sTotalMoney ?? 0
            let moneyStr = "\(String(format: "%.2f", money))"
            
            let calculateNum = beforeMoney - money
            let calStr = "\(String(format: "%.2f", calculateNum))"
            
            
            let alert = ZyaFoodOrdAlert.init(frame: .zero)
            var infos = [(String, String)]()
            infos.append(("下单前金额: ", beforeStr))
            infos.append(("下单金额:", moneyStr))
            infos.append(("下单后金额:", calStr))
            alert.show(infos: infos) {
                doActionNetwork()
            }
            
            
//        } else {
//            doActionNetwork()
//        }
        
        func doActionNetwork() {
            var api:API!
            if excuteType == .add || excuteType == .copy {
                api = API.pFoodSave(data: dictionaryToJson(model.dictionaryRepresentation()))
            } else {
                api = API.pFoodUpdate(data: dictionaryToJson(model.dictionaryRepresentation()))
            }
            
            KSNetwork.shared.doRequest(api) { (data: BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    KSToast(data.errorCombine.unwrap)
                    if let clo = self.refreshClosure {
                        clo()
                    }
                    self.navigationController?.popViewController(animated: true)
                    
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
        }
    }
    
    
}
extension ZyaFoodOrderFormVC {
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: ZyaFoodOrderFormCell.identifier, for: indexPath) as? ZyaFoodOrderFormCell else {
            fatalError()
        }
        cell.excuteType = self.excuteType
         cell.one = model.detail[indexPath.row]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        if TenderAppear.shared.projectType == .awClient {
            let one = model.detail[indexPath.row]
            
            let text = one.sName.unwrap + "  " + one.sSpec.unwrap + " " + one.sCompanyGoodsTreeNm.unwrap
            let lab = UILabel().easy(text, nil, .systemFont(ofSize: 15))
                .extFrameSize(size: CGSize(width: KS_SCREEN_WIDTH - 62, height: CGFloat.greatestFiniteMagnitude))
            lab.sizeToFit()
            if lab.ks_height > 16 {
                return 120
            }
            return 100
//        } else {
//            return 100
//        }
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return model.detail.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if excuteType == .view {
            return
        }
        let one = self.model.detail[indexPath.row]
        
        let newsView = ZyaEditProductView(frame:CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: KSGlobal.screenH))
        newsView.titleLab.text = one.sName
        newsView.item1.setVal(one.sSpec.unwrap)
        newsView.item2.setVal(one.sPrice.unwrap + "元/Kg")
        newsView.item3.setVal(one.sWeightRatio.unwrap)
        newsView.item4.setVal(one.sWeight.unwrap)
        newsView.item5.setVal(one.sAuxNum.unwrap)
        newsView.item6.setVal(one.sMoney.unwrap + "元")
        newsView.item7.setVal(one.sRemark.unwrap)
        newsView.deleteClosure = { [indexPath] in
            alertUtil(self, title: "确认删除", operateS: [nameAction(name: "确定", action: { _ in
                self.model.detail.remove(at: indexPath.row)
                newsView.removeFromSuperview()
                self.tableVw.reloadData()
                self.configBottom()
            })])
        }
        newsView.confirmClosure = { [indexPath] in
            self.model.detail[indexPath.row].sAuxNum =  newsView.item5.textView.text.unwrap
            
            self.model.detail[indexPath.row].sWeight =  newsView.item4.textView.text.unwrap
            self.model.detail[indexPath.row].sNum = self.model.detail[indexPath.row].sWeight
            
            self.model.detail[indexPath.row].sRemark =  newsView.item7.textView.text.unwrap
            
            self.countMoneyAndMTax(row: indexPath.row)
            
            newsView.removeFromSuperview()
            self.tableVw.reloadData()
            self.configBottom()
        }
        
        
        UIApplication.shared.keyWindow!.rootViewController!.view!.addSubview(newsView)
        
        
    }
    
    func countMoneyAndMTax(row:Int) {
        self.model.detail[row].sMoney =  "\((doubleTran(self.model.detail[row].sWeight) * doubleTran(self.model.detail[row].sPrice)).roundTo(2))"
        
        
        //            税额（税额=实际金额*税率%/(1+税率%)，保留两位小数点）
        let mtax = doubleTran(self.model.detail[row].sMoney) * (doubleTran(self.model.detail[row].sTax) / 100) / ( 1 + doubleTran(self.model.detail[row].sTax) / 100)
        self.model.detail[row].sMoneyTax = "\(mtax.roundTo(2))"
    }
}
class ZyaLLLXButton: UIButton {
    
    override func layoutSubviews() {
        super.layoutSubviews()
        imageView?.frame =  CGRect(x: 0 , y: 7, width: 26, height: 26)
        titleLabel?.frame = CGRect(x: 33 , y: 0, width: self.frame.width, height: self.frame.height)
    }
    
}
